/*
 * login into system.
 */

var genTok = require("../token/gentok.js");
var passwordTable = require("../Redis/passwordTable.js");
var redis = require("../Redis/redis.js");

exports.login = function(req, res) {
	"use strict";
	var query = req.query;
	if (!query) {
		res.render("login", {
			title : "Login"
		});
		return;
	}
	var account = query.userid;
	var password = query.pswrd;
	if (!account || !password) {
		res.render("login", {
			title : "Login"
		});
		return;
	}

	if (account !== "admin") {
		res.send("account not exist");
		return;
	}

	var context = redis.getContext();

	passwordTable.loadPassword(context, "ocean", function(err, reply) {
		if (err) {
			res.send("" + err);
		} else {
			if (reply) {
				reply = "" + reply;
				if (password !== reply) {
					res.send("password not match");
					return;
				}
			} else if (password !== "linguohua123") {
				res.send("password not match");
				return;
			}

			var tk = genTok.gen(account);
			res.cookie("tk", tk, {
				maxAge : 30 * 60 * 1000,
				httpOnly : true
			});

			res.send("ok");
		}
	});
};

exports.logout = function(req, res) {
	"use strict";
	res.clearCookie("tk");
	res.redirect("/login");
};

exports.setPassword = function(req, res) {
	"use strict";

	var result = {
		title : "Setting the password",
	};
	res.render("setPassword", result);
};

exports._savePassword = function(req, res) {
	"use strict";
	var password = req.body.password;

	var context = redis.getContext();

	passwordTable.setPassword(context, "ocean", password, function(err) {
		if (err) {
			console.error(err);
			res.send("" + err);
		} else {
			res.clearCookie("tk");
			res.send("ok");
		}
	});

};

exports.login.cookieFree = true;
